/*
 * Sw_Timers.c
 *
 *  Created on: 29/10/2012
 *      Author: uidv1378
 */

#include "Sw_Timers.h"

SwCounter_t  SwCounterObjArray[MAX_COUNTER_OBJECTS];	/**< Stores the counter objects */
SwTimerObj_t SwTimerObjArray[MAX_TIMER_OBJECTS];		/**< Stores the timer objects */

uint8 AssignedTimersIndex = 0;		/**< Will count the timers that are created on the application */
uint8 AssignedCountersIndex = 0;	/**< Will count the counters that are created on the application */


void SwTimer_Init(void)
{
	uint8 i;
	for (i=0; i<MAX_TIMER_OBJECTS; i++)
	{
		SwTimerObjArray[i].timerCount = INACTIVE_TIMER;	/* Set all timers inactive */
		SwTimerObjArray[i].timerEvent = NULL;
		SwTimerObjArray[i].bEventFlag = FALSE;
	}	
	
	for (i=0; i<MAX_COUNTER_OBJECTS; i++)
	{
		SwCounterObjArray[i].timerCount = INACTIVE_TIMER;	/* Set all timers inactive */
	}
			
	AssignedTimersIndex = 0;
	AssignedCountersIndex = 0;
	
	EVHD_vRegister(EV_SwTimer_Event); /*Register the SW timer Event in the system*/
}

void SwTimer_ISR(void)
{
	uint8 i;

	for (i=0; i<AssignedTimersIndex; i++)
	{
		if (SwTimerObjArray[i].timerCount != INACTIVE_TIMER)	/* only decrement active timers */
		{				
			if(SwTimerObjArray[i].timerCount >= SwTimer__nDecrementV)
			{
				SwTimerObjArray[i].timerCount -= SwTimer__nDecrementV;
			}
			else
			{
				SwTimerObjArray[i].timerCount = 0;
			}				
			
			if(SwTimerObjArray[i].timerCount == 0)	/* if timer has elapsed */
			{					
				if (SwTimerObjArray[i].timerEvent != NULL)
				{	
					SwTimerObjArray[i].timerCount = INACTIVE_TIMER;	/* disable timer */
					SwTimerObjArray[i].bEventFlag = TRUE;	/* Enable Timer event flag */	
					EVHD_vSendEvent(EV_SwTimer_Event);		/* Send SwTimer event */
				}					
			}
		}
	}		
}

void SwTimer_EventHandler(void)
{
	uint8 i;

	for (i=0; i<AssignedTimersIndex; i++)
	{
		if(TRUE == SwTimerObjArray[i].bEventFlag){
			SwTimerObjArray[i].bEventFlag = FALSE;
			SwTimerObjArray[i].timerEvent();		/* execute timer callback function */
		}		
	}
	
}

uint8 SwTimer_CreateTimer(pFunc_t callBackFunc)
{
	uint8 timerId;
	
	if (AssignedTimersIndex < MAX_TIMER_OBJECTS)
	{
		if (callBackFunc != NULL)
		{
			SwTimerObjArray[AssignedTimersIndex].timerEvent = callBackFunc;	
		}
		timerId = AssignedTimersIndex++;
	}
	else
	{
		timerId = INVALID_TIMER_ID;
	}
	
	return timerId;
}


void SwTimer_StartTimer(uint8 timerId, uint16 tickPeriod_ms)
{
	SwTimerObjArray[timerId].timerCount = tickPeriod_ms;
}


void SwTimer_StopTimer(uint8 timerId)
{
	SwTimerObjArray[timerId].timerCount = INACTIVE_TIMER;
}


uint8 SwTimer_HasElapsed(uint8 timerId)
{
	if (SwTimerObjArray[timerId].timerCount == 0)
	{
		SwTimerObjArray[timerId].timerCount = INACTIVE_TIMER;
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}


